package com.xiaolin.token.controller;

import com.xiaolin.token.model.Member;
import com.xiaolin.token.service.MemberService;
import com.xiaolin.token.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName JwtLoginController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/9/30
 * @Version 1.0
 */
@Controller
public class TokenLoginController {
    @Autowired
    MemberService memberService;

    /**
     * 用户登录
     * @param member 只要参数名与对象属性对应上，表单数据会自动封装成对象
     * @param response
     * @param request @RequestParam("username") String username, @RequestParam("password") String password
     * @return
     * @throws IOException
     */
    @RequestMapping("/tokenLogin")
    public void login(Member member, HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        String contextPath = request.getContextPath();
        if(StringUtils.isEmpty(member.getUsername()) || StringUtils.isEmpty(member.getPassword())){
            response.sendRedirect(contextPath+"/error");
            return;
        }
        Member one = memberService.selectByName(member.getUsername());
        if(one ==null || !one.getUsername().equals(member.getUsername()) || !one.getPassword().equals(member.getPassword())){
            response.sendRedirect(contextPath+"/error");
            return;
        }
        //创建token
        String token = TokenUtils.createToken(one.getUsername(), one.getPassword());
        // 将token设置到cookie(也可以设置到header，设置到header时需要前端获取header的token，再携带到后端)
        Cookie cookie=new Cookie("token",token);
        cookie.setMaxAge(10);
        response.addCookie(cookie);
        // 设置到header
        //response.setHeader("Authorization",token);
        response.sendRedirect(request.getContextPath()+"/index.html");
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        for (Cookie cookie : request.getCookies()) {
            // 设置cookie过期
            if("token".equals(cookie.getName())){
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        return "login-token";
    }
}
